#include "main.h"

static HWND next_clipboard_viewer;
static char *clipboard;
static BOOL stopped;

extern char *get_clipboard(void)
{
	return clipboard;
}

static void refresh(void)
{
	HGLOBAL hGlobal;
	
	if (stopped)
		return;
	
	OpenClipboard(main_window);
	
	if (!(hGlobal = GetClipboardData(CF_TEXT)))
		goto end;
	
	if (clipboard)
		free(clipboard);
	clipboard = malloc(GlobalSize(hGlobal) + 1);	
	strcpy(clipboard, GlobalLock(hGlobal));
	GlobalUnlock(hGlobal);

end:
	CloseClipboard();
}

extern void stop_clipboard_monitor(void)
{
	if (next_clipboard_viewer)
	{
		ChangeClipboardChain(main_window, next_clipboard_viewer);
		next_clipboard_viewer = 0;
	}
			
	if (clipboard)
	{
		free(clipboard);
		clipboard = 0;
	}
	
	stopped = TRUE;
}

extern void activate_clipboard_monitor(void)
{
	next_clipboard_viewer = SetClipboardViewer(main_window);
	stopped = FALSE;
	refresh();
}

extern void clipboard_monitor(UINT msg, WPARAM wParam, LPARAM lParam)
{
	switch (msg)
	{	
		case WM_DESTROY:
			stop_clipboard_monitor();
			break;
		
		case WM_DRAWCLIPBOARD:
			if (next_clipboard_viewer)
				SendMessage(next_clipboard_viewer, msg, wParam, lParam);
			refresh();
			break;
		
		case WM_CHANGECBCHAIN:
			if (wParam == next_clipboard_viewer)
				next_clipboard_viewer = lParam;
			else if (next_clipboard_viewer)
				SendMessage(next_clipboard_viewer, msg, wParam, lParam);
			break;
	}
}